public class BinarySearchTree {

    static class TreeNode {
        public int key;
        public TreeNode left;
        public TreeNode right;

        TreeNode(int key) {
            this.key = key;
        }
    }

    public TreeNode root;

    /**
     * 插入一个元素
     * @param key
     */
    public void insert(int key) {
        if (root == null){
            root = new TreeNode(key);
            return;
        }
        TreeNode cur = root;
        TreeNode parent = null;
        while (cur != null){
            if (cur.key < key){
                parent = cur;
                cur = cur.right;
            }else if (cur.key > key){
                parent = cur;
                cur = cur.left;
            }else {
                return ;
            }
        }
        TreeNode Node = new TreeNode(key);
        if (parent.key < key){
            parent.right = Node;
        }else {
            parent.left = Node;
        }
    }
    //查找key是否存在
    public boolean search(int key) {
        TreeNode cur = root;
        while (cur != null){
            if (cur.key < key){
                cur = cur.right;
            }else if (cur.key > key){
                cur = cur.left;
            }else {
                return true;

            }
        }
        return false;
    }
    //删除key的值
    public void remove(int key) {
       TreeNode cur = root;
       TreeNode parent = null;
       while(cur != null){
           if(cur.key < key){
               parent =cur;
               cur = cur.right;
           }else if (cur.key > key){
               parent = cur;
               cur = cur.left;
           }else {
               removeNode(parent,cur);
           }
       }
    }
    private  void removeNode(TreeNode parent,TreeNode cur){
        if (cur.left == null){
            if (cur == root){
                root = cur.right;
            }else if (cur == parent.left){
                parent.left = cur.right;
            }else {
                parent.right = cur.right;
            }
        }else if (cur.right == null){
            if (cur == root){
                root = cur.left;
            } else if (cur == parent.left) {
                parent.left = cur.left;
            }else {
                parent.right = cur.left;
            }
        }else {
            TreeNode tp = cur;
            TreeNode t = cur.right;
            while(t.left != null){
                tp = t;
                t = cur.left;
            }
            cur.key = t.key;

            if(tp.left == t){
                tp.left = t.right;
            }else {
                tp.right = t.right;

            }
        }
    }
}